package com.anjbo.controller.house;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import com.anjbo.bean.order.OrderThirdDto;
import com.anjbo.common.RespDataObject;
import com.anjbo.common.RespHelper;
import com.anjbo.common.RespStatusEnum;
import com.anjbo.service.house.HouseDataService;
import com.anjbo.service.house.HouseService;
import com.anjbo.service.order.OrderThirdService;
import com.anjbo.utils.DateUtil;
import com.anjbo.utils.LoginCacheUtil;
import com.anjbo.utils.StringUtil;

@RequestMapping("/app/house/data")
@Controller
public class HouseDataController {
	
	@Resource
	private HouseDataService houseDataService;
	
	@Resource
	private HouseService houseService;
	
	@Resource
	private OrderThirdService orderThirdService;
	
	/**
	 * B端首页
	 * @param request
	 * @param param
	 * @return
	 */
	@RequestMapping("/selectHouseData")
	@ResponseBody
	public RespDataObject<Map<String, Object>> selectHouseData(
			HttpServletRequest request, @RequestBody final Map<String, Object> param) {
        RespDataObject<Map<String,Object>> resp = new RespDataObject<Map<String, Object>>();
        try {
        	//创建线程池同时处理三个任务
			final Map<String,Object> resultMap = new HashMap<String, Object>();
			
			ExecutorService pool = Executors.newFixedThreadPool(3);
			
			pool.execute(new Runnable() {
				@Override
				public void run() {
					resultMap.put("secondhouseData", getSecondhousing(param));
				}
			});
			
			pool.execute(new Runnable() {
				@Override
				public void run() {
					resultMap.put("myAssets", getMyAssets(param));
				}
			});
			
			pool.execute(new Runnable() {
				@Override
				public void run() {
					resultMap.put("newYunOrder", getNewYunOrder(param));
				}
			});
			
			pool.shutdown();

			while (true) {  
			    if (pool.isTerminated()) {
			        RespHelper.setSuccessDataObject(resp,resultMap);
			        return resp;
			    }
			}
		} catch (Exception e) {
			e.printStackTrace();
			RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
	        return resp;
		}
	}
	
	/**
	 * 查云按揭最新的记录
	 * @param param
	 * @return
	 */
	private OrderThirdDto getNewYunOrder(Map<String, Object> param){
		OrderThirdDto orderThirdDto = new OrderThirdDto();
		String city = MapUtils.getString(param, "city");
		if ("深圳".equals(city)) {
			orderThirdDto.setType(12);
		} else {	//其他地区展示二手房
			orderThirdDto.setType(1);
		}
		orderThirdDto.setUid(LoginCacheUtil.getUid(MapUtils.getString(param, "sid"), MapUtils.getString(param, "deviceId")));
		orderThirdDto =orderThirdService.selectNewByUid(orderThirdDto);
		if (orderThirdDto != null) {
			if (12 ==orderThirdDto.getType()) {
				orderThirdDto.setLoanAmount(orderThirdDto.getLoanAmount()/10000);
			}
			orderThirdDto.setCertificateNo(StringUtil.doCertificateNo(orderThirdDto.getCertificateNo()));
		}
		return orderThirdDto;
	}
	
	/**
	 * 我的资产
	 * @param param
	 * @return
	 */
	private Map<String,Object> getMyAssets(Map<String, Object> param) {
		param.put("uid", LoginCacheUtil.getUid(MapUtils.getString(param, "sid"), MapUtils.getString(param, "deviceId")));
		 
		Map<String, Object> resultMap = houseService.selectHouseAssetByIndex(param);
		if (resultMap == null) {
			resultMap = new HashMap<String, Object>();
		} 
		if (MapUtils.getDouble(resultMap, "sumPrice") == null || MapUtils.getDouble(resultMap, "appreciation") == null) {
			resultMap.put("sumPrice", 0);
			resultMap.put("appreciation", 0);
		} else {
			double sumPrice = MapUtils.getDouble(resultMap, "sumPrice");	//转成万元
			double appreciation = MapUtils.getDouble(resultMap, "appreciation");
			resultMap.put("sumPrice", sumPrice);
			resultMap.put("appreciation", appreciation);
		}
		return resultMap;
	}
	
	/**
	 * 二手房数据
	 * @param param
	 * @return
	 */
	private Map<String,Object> getSecondhousing(Map<String, Object> param) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
        
        String city = MapUtils.getString(param, "city");
        if ("东莞".equals(city)) {
        	param.put("tableName", "tbl_app_task_dealdata_dongguan_data");
        } else if ("惠州".equals(city)) {
        	param.put("tableName", "tbl_app_task_dealdata_huizhou_data");
        } else if ("广州".equals(city)) {
        	param.put("tableName", "tbl_app_task_dealdata_guangzhou_data");
        } else if ("厦门".equals(city)) {
        	param.put("tableName", "tbl_app_task_dealdata_xiamen_data");
        } else {
        	param.put("tableName", "tbl_app_task_dealdata_shenzhen_secondhand");
        }
        List<Map<String,Object>> dayDataList = houseDataService.selectDayTotalNumHomePage(param);
        if (dayDataList != null) {
        	Collections.reverse(dayDataList);
        }
    	resultMap.put("dayData", dayDataList);
    	resultMap.put("newestMonthData", houseDataService.selectNewestMonthTotalNumHomePage(param));
    	resultMap.put("newestDayData", houseDataService.selectNewestDayTotalNumHomePage(param));
    	//给不足12个月的城市追加数据
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> newMonthDataList = houseDataService.selectMonthTotalNumHomePage(param);
        if (newMonthDataList.size() < 12) {
        	if ("东莞".equals(city)) {
        		
            } else if ("惠州".equals(city)) {
            	
            } else if ("广州".equals(city)) {
            	
            } else if ("厦门".equals(city)) {
            	
            } else {
            	param.put("tableName", "tbl_app_task_dealdata_shenzhen_ext");
                List<Map<String,Object>> oldMonthDataList = houseDataService.selectMonthTotalNumHomePage(param);
                additionalData(dataList,newMonthDataList, oldMonthDataList);
                newMonthDataList = dataList;
            }
        }
    	resultMap.put("monthData", newMonthDataList);
        return resultMap;
	}

	/**
	 * 追加数据
	 * @param newMonthDataList	被追加数据
	 * @param oldMonthDataList	追加数据
	 * @return
	 */
	private List<Map<String,Object>> additionalData(List<Map<String,Object>> dataList,List<Map<String,Object>> newMonthDataList,List<Map<String,Object>> oldMonthDataList) {
		List<String> mothList = DateUtil.getMothDescList(12);
		Collections.reverse(mothList);
		first:for (String moth : mothList) {
			for (Map<String,Object> maps : newMonthDataList) {
				if (moth.equals(MapUtils.getString(maps, "date"))) {
					dataList.add(maps);
					continue first;
				}
			}
			for (Map<String,Object> maps : oldMonthDataList) {
				if (moth.equals(MapUtils.getString(maps, "date"))) {
					dataList.add(maps);
					break;
				}
			}
		}
		return dataList;
	}
}
